﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using orienta.Code.JQgrid;
using orienta.Helper;
using orienta.Models;
using orienta.Utils;
using orienta.ViewModels;
using orienta.Code;

namespace orienta.Controllers
{
    public class PersonaController : Controller
    {
        //
        // GET: /Persona/
        private GoodTireEntities db = new GoodTireEntities();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public virtual JsonResult Listar(GridTable grid)
        {
            var jqgrid = new JQgrid();
            var personaHelper = new PersonaHelper();
            try
            {
                var cantidad = personaHelper.Contar();
                var totalPaginas = 0;

                grid.page = (grid.page == 0) ? 1 : grid.page;

                grid.rows = (grid.rows == 0) ? 100 : grid.rows;

                var where = (Utils.Utils.GetWhere(grid.filters, grid.rules));

                if (!string.IsNullOrEmpty(where))
                {
                    grid._search = true;

                    if (!string.IsNullOrEmpty(grid.searchString))
                    {
                        where = where + " and ";
                    }
                }
                if (cantidad > 0 && grid.rows > 0)
                {
                    var div = cantidad / (decimal)grid.rows;
                    var round = Math.Ceiling(div);
                    totalPaginas = Convert.ToInt32(round);
                    totalPaginas = totalPaginas == 0 ? 1 : totalPaginas;
                }

                grid.page = grid.page > totalPaginas ? totalPaginas : grid.page;

                var start = grid.rows * grid.page - grid.rows;
                if (start < 0) start = 0;

                jqgrid.total = totalPaginas;
                jqgrid.page = grid.page;
                jqgrid.records = cantidad;
                jqgrid.start = start;

                var lista = personaHelper.Buscar(grid.rows, grid.page, grid.sidx, grid.sord,where);

                jqgrid.rows = lista.Select(item => new JRow
                {
                    id = item.nIdePersona.ToString(),
                    cell = new[]
                    {
                            item.nIdePersona.ToString(),
                            item.nIdeTipoPer.ToString(),
                            item.vTipoPersona,
                            item.nIdeTipoDocum.ToString(),
                            item.vTipoDocum,
                            item.vNumDocum,
                            item.nIdeCodPaisDoc.ToString(),
                            item.vPais,
                            item.vPriNombre,
                            item.vSegNombre,
                            item.vPriApellido,
                            item.vSegApellido,
                            item.nIdeTipoGenero.ToString(),
                            item.vTipoGenero,
                            item.dtFecNacim.ToString("dd/MM/yyyy"),
                            item.vEmail,
                            item.vTelefono1,
                            item.vTelefono2,
                            item.dtFecReg.ToString("dd/MM/yyyy"),
                            item.dtFecIniVig.ToString("dd/MM/yyyy"),
                            item.dtFecFinVig.ToString(),
                            item.nIdeUsuReg.ToString()
                    }
                }).ToArray();
            }
            catch (Exception ex)
            {
                //MostrarError(ex.Message);
            }

            return Json(jqgrid);
        }

        public virtual ActionResult Crear()
        {
            try
            {
                var entidad = new PersonasView()
                {
                    vPriApellido = string.Empty
                };
                CargarCombos();
                ViewBag.Accion = "Crear";
                return PartialView("Edit", entidad);
            }
            catch (Exception ex)
            {
                ViewBag.Accion = "Error";
                throw;
            }
        }

        [HttpPostAttribute]
        public virtual JsonResult Crear(PersonasView entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    var personaHelper = new PersonaHelper();
                    var resultado = personaHelper.InsertarPersona(entidad);

                    if (resultado != 0)
                    {
                        jsonResponse.Success = true;
                        jsonResponse.Message = Constantes.MensajeConfirmacion;
                    }
                    else
                    {
                        jsonResponse.Success = false;
                        jsonResponse.Message = Constantes.MensajeError;
                    }
                }
                catch (Exception ex)
                {
                    jsonResponse.Success = false;
                    jsonResponse.Message = Constantes.MensajeError;
                }
            }
            else
            {
                jsonResponse.Message = Constantes.MensajeRequeridos;
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
        
        public virtual ActionResult Modificar(string id)
        {
            var personaHelper = new PersonaHelper();
            try
            {
                var entidad = personaHelper.Single(Convert.ToInt32(id));
                 
                CargarCombos();
                ViewBag.Accion = "Modificar";
                return PartialView("Edit", entidad);
            }
            catch (Exception ex)
            {
                ViewBag.Accion = "Error";
                throw;
            }
            
        }

        [HttpPostAttribute]
        public virtual JsonResult Modificar(PersonasView entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
         
        public void CargarCombos()
        {
            HtmlUtils htmlUtils = new HtmlUtils();
            ViewBag.Documento = htmlUtils.getComboTipoDocumento();
            ViewBag.Pais = htmlUtils.getComboPais();
            ViewBag.Genero = htmlUtils.getComboTipoGeneroPersona();
            ViewBag.TipoPersona = htmlUtils.getComboTipoSolicitante();
        }

        public virtual JsonResult BuscarPersona(GridTable grid)
        {
            var jqgrid = new JQgrid();
            var personaHelper = new PersonaHelper();
            try
        {

                var totalPaginas = 0;
                grid.page = (grid.page == 0) ? 1 : grid.page;
                grid.rows = (grid.rows == 0) ? 100 : grid.rows;
                var where = (Utils.Utils.GetWhere(grid.filters, grid.rules));
                if (!string.IsNullOrEmpty(where))
                {
                    grid._search = true;
                    if (!string.IsNullOrEmpty(grid.searchString))
                    {
                        where = where + " and ";
                    }
                }
                var cantidad = personaHelper.Contar(where);
                if (cantidad > 0 && grid.rows > 0)
                {
                    var div = cantidad / (decimal)grid.rows;
                    var round = Math.Ceiling(div);
                    totalPaginas = Convert.ToInt32(round);
                    totalPaginas = totalPaginas == 0 ? 1 : totalPaginas;
                }
            
                grid.page = grid.page > totalPaginas ? totalPaginas : grid.page;
                var start = grid.rows * grid.page - grid.rows;
                if (start < 0) start = 0;
                jqgrid.total = totalPaginas;
                jqgrid.page = grid.page;
                jqgrid.records = cantidad;
                jqgrid.start = start;

                var lista = personaHelper.BuscarPersona(grid.rows, grid.page, grid.sidx, grid.sord, where);

                jqgrid.rows = lista.Select(item => new JRow
                {
                    id = item.nIdePersona.ToString(),
                    cell = new[]
                    {
                            item.nIdePersona.ToString(),
                            item.nIdeTipoDocum.ToString(),
                            item.vNumDocum.ToString(),
                            item.vPriApellido,
                            item.vSegApellido,
                            item.vPriNombre,
                            item.vSegNombre
                    }
                }).ToArray();
                }
                catch (Exception ex)
                {
                String e = ex.ToString();
                //MostrarError(ex.Message);
                }
            
            return Json(jqgrid);
        }
    }
}
